package org.tigris.atlas.xml.schema.mda.generator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.tigris.atlas.mda.generator.GenerationContext;
import org.tigris.atlas.mda.metadata.MetadataRepository;
import org.tigris.atlas.mda.metadata.element.Entity;
import org.tigris.atlas.mda.metadata.element.Operation;
import org.tigris.atlas.mda.metadata.element.Service;
import org.tigris.atlas.xml.schema.mda.element.SchemaEntity;

public class SchemaCollectionServiceResponseGenerator extends AbstractSchemaServiceResponseGenerator {
	
	private Log log = LogFactory.getLog(SchemaCollectionServiceResponseGenerator.class);
	
	/**
	 * @see org.tigris.atlas.mda.codegen.generator.schema.AbstractSchemaServiceResponseGenerator#shouldGenerate(org.tigris.atlas.mda.codegen.element.java.JavaOperation)
	 */
	protected boolean shouldGenerate(Operation operation) {
		return  isCollectionResponse(operation);
	}
	
	/**
	 * @see org.tigris.atlas.mda.codegen.generator.service.AbstractServiceResponseJavaGenerator#setupContext(org.tigris.atlas.mda.codegen.generator.GenerationContext, org.tigris.atlas.mda.codegen.element.java.JavaService, org.tigris.atlas.mda.codegen.element.java.JavaOperation)
	 */
	protected VelocityContext setupContext(GenerationContext context, Service service, Operation operation) {	
		String applicationName = context.getArtifactId();
		 VelocityContext vc = super.setupContext(context, service, operation);
		 
		 //this template is also used to generate responses for entities from the 
		 //entity maintenance server, so the properties are a little more abstract:
		 vc.put("responseName", operation.getName());
		 
		 String entityName = operation.getReturnManyType();
		 Entity entity = (Entity)MetadataRepository.getInstance().getAllEntities(applicationName).get(entityName);
		 if (entity == null) {
			 log.error("Service '" + service.getName() + "' has operation '" + operation.getName() + 
			 	"' that cannot resolve it's entity '" + entityName + "'!");
		 } else {
			 SchemaEntity schemaEntity = new SchemaEntity(entity);
			 vc.put("entity", schemaEntity);
		 }
		 
		 return vc;
	}	

}
